/**
 * 
 */
package com.miolr.core.dao.hibernate;

import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.ParameterizedType;
import java.util.Collection;
import java.util.List;

import javax.inject.Inject;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.transform.Transformers;

import com.miolr.core.dao.GenericDao;
import com.miolr.core.query.PageModel;

/**
 * @author iday
 * 
 */
@SuppressWarnings("unchecked")
public class HibernateGenericDao<T> implements GenericDao<T> {

	@Inject
	private SessionFactory sessionFactory;
	private Log logger = LogFactory.getLog(this.getClass());
	private Class<T> persistentClass;

	public HibernateGenericDao() {
		super();
		if (this.persistentClass == null) {
			try {
				this.persistentClass = (Class<T>) ((ParameterizedType) this
						.getClass().getGenericSuperclass())
						.getActualTypeArguments()[0];
			} catch (Exception e) {
				logger.error("persistentClass init error.", e);
			}
		}
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public Session getCurrentSession() {
		try {
			return this.sessionFactory.getCurrentSession();
		} catch (HibernateException e) {
			return this.sessionFactory.openSession();
		}
	}

	@Override
	public void initLazeProperties(Object t, String... nestedNames) {
		for (String property : nestedNames) {
			try {
				PropertyUtils.getProperty(t, property);
			} catch (IllegalAccessException e) {
				logger.error(
						"initLaze lozy property [" + property
								+ "] error in Object ["
								+ t.getClass().getName() + "].", e);
				continue;
			} catch (InvocationTargetException e) {
				logger.error(
						"initLaze lozy property [" + property
								+ "] error in Object ["
								+ t.getClass().getName() + "].", e);
				continue;
			} catch (NoSuchMethodException e) {
				logger.error(
						"initLaze lozy property [" + property
								+ "] error in Object ["
								+ t.getClass().getName() + "].", e);
				continue;
			}
		}
	}

	@Override
	public T findByPrimaryKey(Serializable key) {
		return (T) this.getCurrentSession().load(this.persistentClass, key);
	}

	@Override
	public List<T> findAll() {
		return this.getCurrentSession().createCriteria(this.persistentClass)
				.list();
	}

	public List<T> findAll(String sql, boolean cached, Object... params) {
		Query q = this.getCurrentSession().createQuery(sql);
		for (int i = 0; i < params.length; i++) {
			Object object = params[i];
			q.setParameter(i, object);
		}
		return q.setCacheable(cached).list();
	}

	public T findOne(String sql, boolean cached, Object... params) {
		Query q = this.getCurrentSession().createQuery(sql);
		for (int i = 0; i < params.length; i++) {
			Object object = params[i];
			q.setParameter(i, object);
		}
		return (T) q.setCacheable(cached).uniqueResult();
	}

	@Override
	public T findOne(DetachedCriteria detachedCriteria, boolean cached) {
		return (T) detachedCriteria.getExecutableCriteria(getCurrentSession())
				.setCacheable(cached).uniqueResult();
	}

	@Override
	public void save(T obj) {
		this.getCurrentSession().save(obj);
	}

	@Override
	public void update(T obj) {
		this.getCurrentSession().update(obj);
	}

	@Override
	public void merge(T t) {
		this.getCurrentSession().merge(t);
	}

	@Override
	public void saveOrUpdate(Collection<T> c) {
		this.getCurrentSession().saveOrUpdate(c);
	}

	@Override
	public void deleteByPrimaryKey(Serializable key) {
		this.delete(this.findByPrimaryKey(key));
	}

	@Override
	public void delete(T obj) {
		this.getCurrentSession().delete(obj);
	}

	@Override
	public void deleteAll(Collection<T> c) {
		for (T obj : c) {
			this.delete(obj);
		}
	}

	@Override
	public List<T> queryAll(final String sql, final boolean cached) {
		return this.getCurrentSession().createQuery(sql).setCacheable(cached)
				.list();
	}

	@Override
	public List<T> queryAll(final String sql) {
		return this.queryAll(sql, false);
	}

	@Override
	public List<T> queryAll(final String sql, final PageModel pm,
			final boolean cached) {
		pm.setTotalRecords((Long) this
				.getCurrentSession()
				.createQuery(
						"select count(*) " + sql.substring(sql.indexOf("from")))
				.setCacheable(cached).uniqueResult());
		return this
				.getCurrentSession()
				.createQuery(sql)
				.setMaxResults(pm.getMaxRecord())
				.setFirstResult(pm.getFirstRecord())
				.setCacheable(cached)
				.setResultTransformer(
						Transformers.aliasToBean(this.persistentClass)).list();
	}

	@Override
	public List<T> queryAll(final String sql, final PageModel pm) {
		return this.queryAll(sql, pm, false);
	}

	@Override
	public List<T> queryAll(DetachedCriteria detachedCriteria, PageModel pm,
			boolean cached, String cacheRegion) {
		Criteria criteria = detachedCriteria
				.getExecutableCriteria(getCurrentSession());
		List<T> list = criteria.setMaxResults(pm.getMaxRecord())
				.setFirstResult(pm.getFirstRecord()).setCacheable(cached)
				.list();
		pm.setTotalRecords(this.count(criteria));
		return list;
	}

	@Override
	public List<T> queryAll(PageModel pm, boolean cached, String cacheRegion) {
		return this.queryAll(DetachedCriteria.forClass(this.persistentClass),
				pm, cached, cacheRegion);
	}

	@Override
	public Long count(Criteria criteria) {
		return (Long) criteria.setProjection(Projections.rowCount())
				.uniqueResult();
	}
}
